--魔尊战场
--#include "data\config\activityconfig\DailyActivity\MoZunConfig.lua" once

MoZunRankName = Lang.Rank.MoZunRank

--战场开始
function MoZunBegin()
	System.broadcastTipmsg(Lang.ScriptTips.MoZun020,ttScreenCenter + ttChatWindow)
    local dVar = System.getDyanmicVar()
    dVar.MoZunBegin = System.getCurrMiniTime()
	--注册大怪刷怪定时器
	dVar.MoZunBigMonTimerIdx = 1  --大怪定时器索引
	Actor.unregScriptCallback( System.getGlobalNpc(), "MobMoZunBigMon")
	local bigTimer = MoZunConfig.Monsters.bigTimer[1]
	Actor.regScriptTimer(System.getGlobalNpc(), 0, bigTimer * 1000, bigTimer * 1000, 1, "MobMoZunBigMon")
	--注册极怪刷怪定时器
	dVar.MoZunLargeMonTimerIdx = 1  --极怪定时器索引
	Actor.unregScriptCallback( System.getGlobalNpc(), "MobMoZunLargeMon")
	local largeTimer = MoZunConfig.Monsters.largeTimer[1]
	Actor.regScriptTimer(System.getGlobalNpc(), 0, largeTimer * 1000, largeTimer * 1000, 1, "MobMoZunLargeMon")	
	--注册定时发放魔能
	Actor.unregScriptCallback( System.getGlobalNpc(), "AutoGiveMoZunEnergy")
	Actor.regScriptTimer(System.getGlobalNpc(), 0, MoZunConfig.randomEnergy.timer * 1000, MoZunConfig.randomEnergy.timer * 1000, -1, "AutoGiveMoZunEnergy")
    InitMoZunRank()
end

--定时发放魔能
function AutoGiveMoZunEnergy()
	local allplayerList = LuaHelp.getSceneActorListById(MoZunConfig.sceneId) or {}
	--先刷选存活
	local playerList = {}
	for i,player in ipairs(allplayerList) do
	    if player and Actor.isDeath(player)== false then
		    table.insert(playerList,player)
		end
	end
	local count = #playerList
	local luckyIdx =  System.getRandomNumber(count) + 1 --幸运者
	for i,player in ipairs(playerList) do
		if player and Actor.isDeath(player)== false then
		    if i == luckyIdx then
			    UpdateMoZunEnergy(player,MoZunConfig.randomEnergy.oneenergy)
				local hScene = Fuben.getSceneHandleById(MoZunConfig.sceneId,0)
				if hScene > 0 then
				    local msg = string.format(Lang.ScriptTips.MoZun009, Actor.getName(player),MoZunConfig.randomEnergy.oneenergy)
				    Fuben.sendMsgToScene(hScene, msg, ttScreenCenter + ttChatWindow)
				end
			else
			    UpdateMoZunEnergy(player,MoZunConfig.randomEnergy.allenergy)
			end
		end
	end
  	
end

--大怪刷怪定时器
function MobMoZunBigMon()
    local dVar = System.getDyanmicVar()
	local idx = dVar.MoZunBigMonTimerIdx or 1
	local maxIdx = #MoZunConfig.Monsters.bigTimer
	if idx > maxIdx then
	    Actor.unregScriptCallback( System.getGlobalNpc(), "MobMoZunBigMon")
	else
        local hScene = Fuben.getSceneHandleById(MoZunConfig.sceneId,0)
		if hScene then
		    local monId = 0 
		    for k,v in ipairs(MoZunConfig.Monsters.big) do
			    Fuben.createMonstersInRange(hScene, v.monid, v.x1, v.y1,v.x2, v.y2, v.count, v.livetime)
				monId = v.monid
			end  
			MobMoZunMsg(monId)
	    end
		--注册下一次定时器
        Actor.unregScriptCallback( System.getGlobalNpc(), "MobMoZunBigMon")
		local nextIdx = idx + 1
		dVar.MoZunBigMonTimerIdx = nextIdx
		if nextIdx <= maxIdx then
		    --时间间隔为下次Timer - 当前Timer
			local timer =  MoZunConfig.Monsters.bigTimer[nextIdx]  - MoZunConfig.Monsters.bigTimer[idx] 
			Actor.regScriptTimer(System.getGlobalNpc(), 0, timer * 1000, timer * 1000, 1, "MobMoZunBigMon")
		end
	end
end 


--极怪刷怪定时
function MobMoZunLargeMon()
    local dVar = System.getDyanmicVar()
	local idx = dVar.MoZunLargeMonTimerIdx or 1
	local maxIdx = #MoZunConfig.Monsters.largeTimer
	if idx > maxIdx then
	    Actor.unregScriptCallback( System.getGlobalNpc(), "MobMoZunLargeMon")
	else
        local hScene = Fuben.getSceneHandleById(MoZunConfig.sceneId,0)
		if hScene then
		    local monId = 0 
		    for k,v in ipairs(MoZunConfig.Monsters.large) do
			    Fuben.createMonstersInRange(hScene, v.monid, v.x1, v.y1,v.x2, v.y2, v.count, v.livetime)
				monId = v.monid
			end
            MobMoZunMsg(monId)			
	    end
		--注册下一次定时器
        Actor.unregScriptCallback( System.getGlobalNpc(), "MobMoZunLargeMon")
		local nextIdx = idx + 1
		dVar.MoZunLargeMonTimerIdx = nextIdx
		if nextIdx <= maxIdx then
		    --时间间隔为下次Timer - 当前Timer
			local timer =  MoZunConfig.Monsters.largeTimer[nextIdx]  - MoZunConfig.Monsters.largeTimer[idx] 
			Actor.regScriptTimer(System.getGlobalNpc(), 0, timer * 1000, timer * 1000, 1, "MobMoZunLargeMon")
		end
	end
end

--刷怪公告
function MobMoZunMsg(monId)
	local hScene = Fuben.getSceneHandleById(MoZunConfig.sceneId,0)
	if  hScene > 0 then
		local monName = System.getMonsterNameById(monId)
		local msg = string.format(Lang.ScriptTips.MoZun015,monName)
		local playerList = LuaHelp.getSceneActorListById(MoZunConfig.sceneId) or {}
	    for i,player in ipairs(playerList) do
		    if player then
		        Actor.sendTipmsg(player,msg,ttActorTop)
		    end
	    end
	end
end

--战场结束
function MoZunEnd()
	System.broadcastTipmsg(Lang.ScriptTips.MoZun021,ttScreenCenter + ttChatWindow)
    local dVar = System.getDyanmicVar()
    dVar.MoZunBegin = nil
    dVar.MoZunEndTime = nil
	Actor.unregScriptCallback( System.getGlobalNpc(), "MobMoZunBigMon")
	Actor.unregScriptCallback( System.getGlobalNpc(), "MobMoZunLargeMon")
	Actor.unregScriptCallback( System.getGlobalNpc(), "AutoGiveMoZunEnergy")
	SendMoZunRankAward()
	ClearActInMoZun()
end

--进入战场
function OnEnterMoZun(sysarg)
	if Actor.getIsDartFlag(sysarg) then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.EscortTips010, ttFlyTip)
		return
	end
	if Actor.getSceneId(sysarg) == MoZunConfig.sceneId then
		return 
	end
    local dVar = System.getDyanmicVar()

    local days = System.getDaysSinceOpenServer()
    if MoZunConfig.openDay > days then
    	Actor.sendTipmsg(sysarg,string.format(Lang.ScriptTips.MoZun019, MoZunConfig.openDay),ttFlyTip)
    	return 
    end

	if not dVar.MoZunBegin then
        Actor.sendTipmsg(sysarg,Lang.ScriptTips.MoZun002,ttFlyTip)
		return	
	end
    --等级
    if Actor.checkActorLevel(sysarg, MoZunConfig.level[2],MoZunConfig.level[1],true) == false then
        Actor.sendTipmsg(sysarg, string.format(Lang.ScriptTips.MoZun003,MoZunConfig.level[2]),ttFlyTip)
		return
	end
	if Actor.isInTeam(sysarg) then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.MoZun016,ttFlyTip)
		return
	end

	--AddDailyActivityDoneNum(sysarg, enDailyActId_MoZunWarScene, 1)	--进入魔尊1次

	--进入场景随机点
	local posIdx = System.getRandomNumber(#MoZunConfig.enterRange) + 1
	Actor.enterScene(sysarg,MoZunConfig.sceneId,MoZunConfig.enterRange[posIdx].x,MoZunConfig.enterRange[posIdx].y)
	--初始化及下发活动面板
	MoZunInitActor(sysarg)
	InitMoZunPanel( sysarg )				--初始化左侧面板

	--Buff
	local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
    local MoShen = GetMoShenConfig(sysarg)
    if  MoShen then
	    for x,y in ipairs(MoShen.buffId or {}) do
	    	if x == vocation then
			    for i,value in ipairs(y or {}) do
			    	Actor.addBuffById(sysarg,value)
				end
			end
		end
	end
	--刷新人物属性
	RefeshActorAttrInMoZun(sysarg)
	--Hp,mp
	ActorHpMpInMoZun(sysarg)

	SendActivityLog(sysarg, ACTIVITY_DEFINE_MOZUN, ActLogStatus_Join, true)

	local sVar = System.getDyanmicVar()
    local time = System.getCurrMiniTime()
    if sVar.MoZunEndTime then
        local lastTime = sVar.MoZunEndTime - time
        local boardStr = Lang.ScriptTips.MoZun023                --注意：字符串中要带有一个 %d
        OpenBoardPanel( sysarg, enBoardPanelStyle_CountDown1, boardStr, lastTime )
    end

    --每天记录进入魔尊战场、盟重杀神的次数，每天只能进行1次（不支持每天开1次以上）
    local todayNum = GetActorDailyDoneTimes( sysarg, enDailyOpTimes_MoZun, nil )
    --print(" dream boss, todayNum="..todayNum)
    if todayNum <= 0 then
        AddActorDailyDoneTimes( sysarg, enDailyOpTimes_MoZun, nil, 1 )
        local actorId = Actor.getActorId( sysarg )
        print(" mozun, first enter, actorId="..actorId)
    end
end

--初始化
function MoZunInitActor(sysarg)
	local ActVar = Actor.getDyanmicVar(sysarg)
	ActVar.MoZunEnergy = 0  --魔能
	ActVar.MoZunLevel  = 1  --等级
	--保存进入时HP,MP
	local hp = Actor.getIntProperty(sysarg,PROP_CREATURE_HP)
	local mp = Actor.getIntProperty(sysarg,PROP_CREATURE_MP)
	ActVar.EnterMoZunHP = hp
	ActVar.EnterMoZunMP = mp
end

--获取魔尊配置
function GetMoShenConfig(sysarg)
    local ActVar = Actor.getDyanmicVar(sysarg)
    local level = ActVar.MoZunLevel or 1
	return MoZunConfig.MoShen[level]
end

--魔能护符被采集
function OnSmallMonDieInMoZun(monster, sysarg, monId)
    for k,v in ipairs(MoZunConfig.Monsters.small) do 
        if v.monid == monId then
		    UpdateMoZunEnergy(sysarg,v.energy)
			break
		end
    end	
end

function OnBigMonDieInMoZun(monster, sysarg, monId)
    for k,v in ipairs(MoZunConfig.Monsters.big) do 
        if v.monid == monId then
		    UpdateMoZunEnergy(sysarg,v.energy)
			local hScene = Fuben.getSceneHandleById(MoZunConfig.sceneId,0)
	        if  hScene > 0 then
	            local actName = Actor.getName(sysarg)
				local monName = System.getMonsterNameById(monId)
				local msg = string.format(Lang.ScriptTips.MoZun014,actName,monName,v.energy)
				Fuben.sendMsgToScene(hScene, msg, ttScreenCenter)
	        end
			break
		end
    end
end

function OnLargeMonDieInMoZun(monster, sysarg, monId)
    for k,v in ipairs(MoZunConfig.Monsters.large) do 
        if v.monid == monId then
		    UpdateMoZunEnergy(sysarg,v.energy)
			local hScene = Fuben.getSceneHandleById(MoZunConfig.sceneId,0)
	        if  hScene > 0 then
	            local actName = Actor.getName(sysarg)
				local monName = System.getMonsterNameById(monId)
				local msg = string.format(Lang.ScriptTips.MoZun014,actName,monName,v.energy)
				Fuben.sendMsgToScene(hScene, msg, ttScreenCenter)
	        end
			break
		end
    end
end


--随机怪被采集
function OnRandomMonDieInMoZun(monster, sysarg, monId)
    if IsInMoZun(sysarg) == false then return end
    local hScene = Fuben.getSceneHandleById(MoZunConfig.sceneId,0)
	if  hScene == 0 then
	    return
	end
    local randNum = System.getRandomNumber(MoZunConfig.RandomNum) + 1
	local num  = 0
	local cfg = nil
	local idx = 0
    for k,v in ipairs(MoZunConfig.RandomEvent)  do
	    num = num + v.rate
		if num >= randNum then
		   cfg = v
		   idx = k
		   break
		end
	end
	--事件处理
	local actName = Actor.getName(sysarg)
	local ActVar = Actor.getDyanmicVar(sysarg)
	if cfg then
	    local msg = ""
        if idx == 1 or idx == 2 or idx == 3 or idx == 6 then
		    local buffCount  =  table.getn(cfg.buffId)
			for i=1,buffCount do
			    local buffId =  cfg.buffId[i]
				 Actor.addBuffById(sysarg,buffId)
			end
			msg = string.format(cfg.msg,actName) 
        elseif idx == 4 or idx == 5 then
      		local x1, y1 = Actor.getEntityPosition(monster, 0, 0)
			x2 = x1 + cfg.monsters.range
			y2 = y1 + cfg.monsters.range
			msg = string.format(cfg.msg,actName,x1,y1)
			Fuben.createMonstersInRange(hScene,cfg.monsters.monid, x1,y1,x2,y2,cfg.monsters.count, cfg.monsters.livetime)
		end
		Fuben.sendMsgToScene(hScene, msg, ttScreenCenter + ttChatWindow)
	end
end


--被击杀
function OnKilledInMoZun(sysarg, killer)
	if(sysarg == nil or killer == nil)then
		return
	end
	if IsInMoZun(sysarg) == false then return end
	if IsInMoZun(killer) == false then return end
	if Actor.isMonster(killer) then
		return
	end
    local actVar = Actor.getDyanmicVar(sysarg)
	local actEnergy = actVar.MoZunEnergy or 0 
	--在保护值范围内
	if actEnergy <= MoZunConfig.killEnergy[1] then
	    UpdateMoZunEnergy(killer,MoZunConfig.killEnergy[2])
	else
	    local actMoShen = GetMoShenConfig(sysarg)
		if actMoShen then
		    local lostEnergy = math.floor(actEnergy * actMoShen.killEnergyRate)
			UpdateMoZunEnergy(sysarg,-lostEnergy) 
			UpdateMoZunEnergy(killer,lostEnergy) 
		end
	end
end

--计算当前等级最大魔能值及最大等级的魔能值
function MoZunLevelMaxEnergy(sysarg)
    local  ActVar = Actor.getDyanmicVar(sysarg)
	local  level = ActVar.MoZunLevel or 1
	local  maxLevel = #MoZunConfig.MoShen
	local  maxEnergy = MoZunConfig.MoShen[maxLevel].energy
	local  cfg = MoZunConfig.MoShen[level+1]
	if not cfg then
	    return maxEnergy,maxEnergy
	end
    return cfg.energy,maxEnergy
end

--更新魔能及等级
function UpdateMoZunEnergy(sysarg,val)
    if IsInMoZun(sysarg) == false then return end
	local  ActVar = Actor.getDyanmicVar(sysarg)
	local  level = ActVar.MoZunLevel or 1
	local  oldLevel = level
	local  maxLevel = #MoZunConfig.MoShen
	local  oldEnergy = ActVar.MoZunEnergy or 0
	local  energy = (ActVar.MoZunEnergy or 0) + val
	local  levelMaxEnergy,MaxEnergy = MoZunLevelMaxEnergy(sysarg)
	if energy < 0 then 
	   energy = 0
	end
	local addVal = energy - oldEnergy
	if addVal > 0 then
	    Actor.sendTipmsg(sysarg,string.format(Lang.ScriptTips.MoZun012,addVal),ttFlyTip)
	elseif addVal < 0 then 
	    Actor.sendTipmsg(sysarg,string.format(Lang.ScriptTips.MoZun013,-addVal),ttFlyTip)
	end
	ActVar.MoZunEnergy = energy
	local updateAll = AddMoZunRank(sysarg,val)
    --重新计算等级
	CalcMoZunLevel(sysarg)
	--更新面板
	if updateAll then
		UpdateMoZunProcessAll()
	else
		UpdateMoZunProcess(sysarg)
	end
	
	--等级变化刷新属性
	if oldLevel ~= ActVar.MoZunLevel then
		--删除buff
		local oldMoshen = MoZunConfig.MoShen[oldLevel]
		if oldMoshen then
			for x,y in ipairs(oldMoshen.buffId or {}) do
				for i,value in ipairs(y or {}) do
				    Actor.delBuffById(sysarg, value)
				end
			end
		end
	    --添加Buff
	    local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
	    local MoShen = GetMoShenConfig(sysarg)
	    if  MoShen then
		    for x,y in ipairs(MoShen.buffId or {}) do
		    	if x == vocation then
				    for i,value in ipairs(y or {}) do
				    	Actor.addBuffById(sysarg,value)
					end
				end
			end
		end
		RefeshActorAttrInMoZun(sysarg)
		--Hp,mp 升级时才自动满血
		if  ActVar.MoZunLevel > oldLevel then
		    ActorHpMpInMoZun(sysarg)
		end
	end
end

--重新计算等级
function CalcMoZunLevel(sysarg)
	local  ActVar = Actor.getDyanmicVar(sysarg)
	local  energy = ActVar.MoZunEnergy or 0
	local level = GetCurMoZunLevelAndValue(energy)
	ActVar.MoZunLevel = level
end

function GetCurMoZunLevelAndValue(energy)
	local  maxLevel = #MoZunConfig.MoShen
	for i=1,maxLevel do
	    local cfg = MoZunConfig.MoShen[i]
		if cfg then
		    if energy < cfg.energy then			    
			    return i - 1, cfg.energy
			end
		end    
	end
	return maxLevel,MoZunConfig.MoShen[maxLevel].energy
end

--刷新人物属性
function RefeshActorAttrInMoZun(sysarg,boClear)
	if boClear then
	    local ActVar = Actor.getDyanmicVar(sysarg)
	    ActVar.MoZunEnergy = nil
	    ActVar.MoZunLevel  = nil
	end
	Actor.collectOperate(sysarg,0)
end

--Hp,Mp处理
function  ActorHpMpInMoZun(sysarg,boRecover)
    local ActVar = Actor.getDyanmicVar(sysarg)
    if boRecover then
		--恢复hp,mp
		local hp = ActVar.EnterMoZunHP or 0
		local mp = ActVar.EnterMoZunMP or 0
		if hp > 0 then
		    Actor.setUIntProperty(sysarg,PROP_CREATURE_HP,hp)
		end
		if mp > 0 then
		    Actor.setUIntProperty(sysarg,PROP_CREATURE_MP,mp)
		end
	else
	   Actor.collectOperate(sysarg,3)
	end
end


--打开左侧面板
function InitMoZunPanel(sysarg)

	if not IsInMoZun( sysarg ) then
		return
	end

	local panelType = 2
	local activityId = enRightPanelActivity_MoZun
	local panelInfo = {}
	
	panelInfo.sts = 1
	
	panelInfo.title = Lang.ScriptTips.MoZunPanel001

	local dVar = System.getDyanmicVar()

	panelInfo.timeTitle = Lang.ScriptTips.MoZunPanel002
	local beginTime 	= dVar.MoZunBegin or 0 
	panelInfo.restTime 	=  MoZunConfig.MoZunTime - ( System.getCurrMiniTime() - beginTime )

	if panelInfo.restTime < 0 then
		panelInfo.restTime = 0
	end

	panelInfo.contentTitle = ""


	local firstName = ""
	local firstScore = 0
	local myIdx = 0
	local myScore = 0
	local ranking = Ranking.getRanking(MoZunRankName)
	if ranking then
		local firstItem = Ranking.getItemFromIndex(ranking, 0)
		if firstItem then
			local firstActorId 	= Ranking.getId(firstItem)
			local firstActor = Actor.getActorById(firstActorId)
			if firstActor then
				firstName = Actor.getName(firstActor)
				firstScore = Ranking.getPoint(firstItem)
				if firstScore < MoZunConfig.energyMin then
					firstName = ""
					firstScore = 0
				end
			end
		end

		local myId 	= Actor.getActorId(sysarg)
		local pItem = Ranking.getItemPtrFromId(ranking, myId)
		if pItem then
			myScore = Ranking.getPoint(pItem)
			if myScore >= MoZunConfig.energyMin then
				myIdx = Ranking.getIndexFromPtr(pItem) + 1
			end
		end
	end

	panelInfo.contents = {}
	if firstScore == 0 then
		panelInfo.contents[1] = Lang.ScriptTips.MoZunPanel003..Lang.ScriptTips.MoZunPanel007
		panelInfo.contents[2] = Lang.ScriptTips.MoZunPanel004..0
	else
		panelInfo.contents[1] = Lang.ScriptTips.MoZunPanel003..firstName
		panelInfo.contents[2] = Lang.ScriptTips.MoZunPanel004..firstScore
	end
	
	if myIdx == 0 then
		panelInfo.contents[3] = Lang.ScriptTips.MoZunPanel005..Lang.ScriptTips.MoZunPanel009
	else
		panelInfo.contents[3] = Lang.ScriptTips.MoZunPanel005..string.format(Lang.ScriptTips.MoZunPanel008, myIdx)
	end
	local level , value = GetCurMoZunLevelAndValue(myScore)
	panelInfo.contents[4] = Lang.ScriptTips.MoZunPanel010..level
	panelInfo.contents[5] = string.format(Lang.ScriptTips.MoZunPanel006, myScore, value)
	
	panelInfo.awardTitle = ""
	panelInfo.awards = {}

	panelInfo.buttons = {1}

	OpenActivityRightPanel( sysarg, panelType, activityId, panelInfo )

end

--左侧面板改变
function UpdateMoZunProcess(sysarg)
	if IsInMoZun(sysarg)== false  then return end
	local panelInfo = {}

	panelInfo.sts = 1

	panelInfo.contentTitle = ""


	local firstName = ""
	local firstScore = 0
	local myIdx = 0
	local myScore = 0
	local ranking = Ranking.getRanking(MoZunRankName)
	if ranking then
		local firstItem = Ranking.getItemFromIndex(ranking, 0)
		if firstItem then
			local firstActorId 	= Ranking.getId(firstItem)
			local firstActor = Actor.getActorById(firstActorId)
			if firstActor then
				firstName = Actor.getName(firstActor)
				firstScore = Ranking.getPoint(firstItem)
				if firstScore < MoZunConfig.energyMin then
					firstName = ""
					firstScore = 0
				end
			end
		end
		local myId 	= Actor.getActorId(sysarg)
		local pItem = Ranking.getItemPtrFromId(ranking, myId)
		if pItem then
			myScore = Ranking.getPoint(pItem)
			if myScore >= MoZunConfig.energyMin then
				myIdx = Ranking.getIndexFromPtr(pItem) + 1
			end
		end
	end

	panelInfo.contents = {}
	if firstScore == 0 then
		panelInfo.contents[1] = Lang.ScriptTips.MoZunPanel003..Lang.ScriptTips.MoZunPanel007
		panelInfo.contents[2] = Lang.ScriptTips.MoZunPanel004..0
	else
		panelInfo.contents[1] = Lang.ScriptTips.MoZunPanel003..firstName
		panelInfo.contents[2] = Lang.ScriptTips.MoZunPanel004..firstScore
	end
	
	if myIdx == 0 then
		panelInfo.contents[3] = Lang.ScriptTips.MoZunPanel005..Lang.ScriptTips.MoZunPanel009
	else
		panelInfo.contents[3] = Lang.ScriptTips.MoZunPanel005..string.format(Lang.ScriptTips.MoZunPanel008, myIdx)
	end
	local level , value = GetCurMoZunLevelAndValue(myScore)
	panelInfo.contents[4] = Lang.ScriptTips.MoZunPanel010..level
	panelInfo.contents[5] = string.format(Lang.ScriptTips.MoZunPanel006, myScore, value)
	
	panelInfo.buttons = {1}

	ChangeActivityRightPanel( sysarg, panelInfo )
end

function UpdateMoZunProcessAll()
	local allplayerList = LuaHelp.getSceneActorListById(MoZunConfig.sceneId) or {}
	if allplayerList then
		for i,player in ipairs(allplayerList) do
		    if player then
			    UpdateMoZunProcess(player)
			end
		end
	end
end

--是否在魔尊战场
function IsInMoZun(sysarg)
    if Actor.getSceneId(sysarg) == MoZunConfig.sceneId then
        return true
	else
	    return false
    end
end

--初始化排行榜
function InitMoZunRank()
	Rank.Init(MoZunRankName, MoZunRankName, {}, 1000, 0)

	local ranking = Ranking.getRanking(MoZunRankName)
	if(ranking == nil)then
		return
	end
	Ranking.clearRanking(ranking)
	Ranking.save(ranking, rankName, true)
end

--加入到排行榜
function AddMoZunRank(sysarg,energy)
	local ranking = Ranking.getRanking(MoZunRankName)
	if ranking then
		local myId 	= Actor.getActorId(sysarg)
		local pItem = Ranking.getItemPtrFromId(ranking, myId)
		if not pItem then
			pItem = Ranking.addItem(ranking, myId,energy)
		else
			Ranking.updateItem(ranking, myId, energy)
		end
		local myIdx = Ranking.getIndexFromPtr(pItem)
		local myScore = Ranking.getPoint(pItem)
		if myScore < MoZunConfig.energyMin then
			return false
		elseif myIdx == 0 then
			return true
		end
	end
	return false
end

--清理玩家个人排行榜分值
function ClearActMoZunRank(sysarg)
	local ranking = Ranking.getRanking(MoZunRankName)
	if ranking then
		local myId 	= Actor.getActorId(sysarg)
		Ranking.removeId(ranking,myId)
	end
end


--[[
按名次，获取魔尊战场积分
rankIdx：名次
]]
function GetMoZunScoreByRankIdx( rankIdx )
	local point = 0
	local ranking = Ranking.getRanking(MoZunRankName)
	if not ranking then
		return point
	end
	local rankItem = Ranking.getItemFromIndex( ranking, idx-1 )    --取第N名记录
	if rankItem then
		point  = Ranking.getPoint(rankItem)
	end
	return point
end

--[[

]]
function GetMoZunScoreByActorId( actorId )
	local point = 0
	local ranking = Ranking.getRanking(MoZunRankName)
	if not ranking then
		return point
	end

	local rankItem = Ranking.getItemIndexFromId( ranking, actorId )    --取第N名记录
	if rankItem then
		point  = Ranking.getPoint(rankItem)
	end
	return point
end



--发魔尊战场奖励
function SendMoZunRankAward()
	local ranking = Ranking.getRanking(MoZunRankName)
	if not ranking then
		return
	end
	local title = Lang.ScriptTips.MoZun010
	local nCount = Ranking.getRankItemCountByLimit(ranking, MoZunConfig.energyMin)
	if nCount > MoZunConfig.RankMax then
		nCount = MoZunConfig.RankMax
	end
	for idx=1, nCount do
		local rankItem = Ranking.getItemFromIndex(ranking, idx-1)    --取第N名记录
		if rankItem then
		    --local point  = Ranking.getPoint(rankItem)
			--if point < MoZunConfig.energyMin then
			--    break
			--end
			local actorId 	= Ranking.getId(rankItem)		
			local content 	= string.format(Lang.ScriptTips.MoZun011, idx)
			local awards	= GetMoZunAwardByRank(idx)
			if awards then
				--SendMail(actorId, title, content, awards)
				Awards.GiveToMailById( actorId, awards, title, content, LogIds.MoZunMailAwardsLogId, Lang.LogTips.MoZunAward)	
			end
		end
	end
	Ranking.clearRanking(ranking)
end

--根据排名获取奖励
function GetMoZunAwardByRank(rank)
    for k,v in ipairs(MoZunConfig.RankAwards) do
        if rank  >= v.rankMin  and  rank <= v.rankMax then
		    return v.awards
		end
    end
	return nil
end

--60秒倒计时
function MoZunDownTime()
	local sVar = System.getDyanmicVar()
    local time = System.getCurrMiniTime()
    sVar.MoZunEndTime = time + 60
	local playerList = LuaHelp.getSceneActorListById(MoZunConfig.sceneId) or {}
	for i,player in ipairs(playerList) do
		if player then
		    local sVar = System.getDyanmicVar()
	        local time = System.getCurrMiniTime()
	        if sVar.MoZunEndTime then
	            local lastTime = sVar.MoZunEndTime - time
	            local boardStr = Lang.ScriptTips.MoZun023                --注意：字符串中要带有一个 %d
	            OpenBoardPanel( player, enBoardPanelStyle_CountDown1, boardStr, lastTime )
	        end
		end
	end
end


--活动结束清理玩家
function ClearActInMoZun()
	local playerList = LuaHelp.getSceneActorListById(MoZunConfig.sceneId) or {}
	for i,player in ipairs(playerList) do
		if player then
		    OnExitMoZun(player)
		    SendActivityLog(player, ACTIVITY_DEFINE_MOZUN, ActLogStatus_Complete, false)
		end
	end
end

--清除玩家Buff
function ClearActBuffInMoZun(sysarg)
    for k,v in ipairs(MoZunConfig.MoShen) do
        for x,y in ipairs(v.buffId or {}) do
        	for i,value in ipairs(y or {}) do
			    Actor.delBuffById(sysarg, value)
			end
		end
	end
    for k,v in ipairs(MoZunConfig.RandomEvent) do
        for x,y in ipairs(v.buffId or {}) do
			Actor.delBuffById(sysarg, y)
		end
	end
end

--魔尊战场安全复活
function OnMoZunRelive(sysarg, reliveType)
	if reliveType and (reliveType == 1 or reliveType == 2) then
		if reliveType and reliveType == 2 then
	    	local posIdx = System.getRandomNumber(#MoZunConfig.enterRange) + 1
			Actor.enterScene(sysarg,MoZunConfig.sceneId,MoZunConfig.enterRange[posIdx].x,MoZunConfig.enterRange[posIdx].y)
	    end

	    --Buff
		local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
	    local MoShen = GetMoShenConfig(sysarg)
	    if  MoShen then
		    for x,y in ipairs(MoShen.buffId or {}) do
		    	if x == vocation then
				    for i,value in ipairs(y or {}) do
				    	Actor.addBuffById(sysarg,value)
					end
				end
			end
		end

		--刷新人物属性
		RefeshActorAttrInMoZun(sysarg)

		ActorHpMpInMoZun(sysarg)
	end
end


--玩家登出游戏
function OnActLoginOutInMoZun(sysarg)
    if IsInMoZun(sysarg) == true  then
	    OnExitMoZun(sysarg)
	end
end

--退出魔尊战场
function OnExitMoZun(sysarg)	
    Actor.enterScene(sysarg,MoZunConfig.leavePos.sceneId, MoZunConfig.leavePos.x, MoZunConfig.leavePos.y,MoZunConfig.leavePos.rang,MoZunConfig.leavePos.rang)
end

function OnExitMoZunHandler(sysarg)
	ActorHpMpInMoZun(sysarg,true)
    CloseBoardPanel( sysarg )
    ClearActMoZunRank(sysarg)
    ClearActBuffInMoZun(sysarg)
    CloseActivityRightPanel(sysarg)
    RefeshActorAttrInMoZun(sysarg,true)
end

function OnMoZunLoginHandler(sysarg)
	ClearActBuffInMoZun(sysarg)
end




